import { createCircleStudyPlanNew, getCircleStudyPlanDetail } from '@/api/Plan';
import { DATEFORMAT, pageOpeTypeEnum } from '@/common';
import { CategoryCascader, getClassViewData } from '@/components/CategoryCascader';
import { SourceSelectModal } from '@/components/SourceSelect';
import Source from '@/components/SourceSelect/Entity/Source';
import YmCollaPanes from '@/components/YmCollaPanes';
import YmEntChoiceStaffModal from '@/components/YmEntChoiceStaffModal';
import YmRegisterPersonSelect from '@/components/YmRegisterPersonSelect';
import { useAppSelector } from '@/redux/store';
import { App, Button, DatePicker, Form, Input, Radio, Select, Space } from 'antd';
import dayjs from 'dayjs';
import { cloneDeep, isEmpty } from 'lodash-es';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { v4 as uuid } from 'uuid';
import { useYmAliOss, YmUpload } from 'ym-design';
import {
  circleTimeOptions,
  dealWidthStudyTemplate,
  getParentCode,
  pictextContentToPicTextContent,
  sourceModalChange,
  studyPlanTypeOptions,
  styleTimeOptions,
  useEntListSelectTreeProps,
  vedioIdOrVideoInfoTransformToVideoList,
} from './common';
import OStyle from './components/index.less';
import StudyPackage from './components/StudyPackage';
import { IStudyPackage, StudyPlanChildProps, StudyPlanChildRef } from './interface';

const requireRules = (text: string) => {
  return [{ required: true, message: text }];
};

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 10 },
};

const AddCircleStudyPlan = forwardRef<StudyPlanChildRef, StudyPlanChildProps>((props, ref) => {
  const {
    message,
    modal: { confirm },
  } = App.useApp();
  const navigator = useNavigate();
  const [form] = Form.useForm();
  const { loginRole } = useAppSelector((state) => state.loginUser);
  const { tradeMap } = useAppSelector((state) => state.commonData);
  const { entId, organizationType } = useAppSelector((state) => state.loginEnt); //organizationType 1:协会，0：企业
  const {
    onStudyPlanMethodChange,
    studyPlanType,
    onStudyPlanTypeChange,
    onSubSuccess,
    onSubError,
    type,
    planCourseId,
    previewDetail,
  } = props;
  let learnMethod = props.learnMethod;
  const [collPanesActiveKeys, setCollPanesActiveKeys] = useState([0, 1]);
  const [modalOpen, setModalOpen] = useState<number>();
  const [classFormItemProps, initRef] = CategoryCascader.useFieldLevelTwo();
  const [loading, setLoading] = useState(false);

  // 使用aliyunoss进行操作
  const customRequest = useYmAliOss();

  //学习对象企业配置
  const EntSelectTree = useEntListSelectTreeProps({
    onSuccess(data) {
      const entList = form.getFieldsValue().entList;
      if (!entList) {
        // 没有就是需要默认给全部
        form.setFieldsValue({
          entList: data.map(({ title, id }) => ({
            entId: id,
            entName: title,
          })),
        });
      }
    },
  });

  //处理提交数据
  const dealWidthFormValues = (values: any) => {
    let finalValue: any = {};
    const {
      cycleTime,
      courseRuleDto,
      studyPackageList,
      courseEffectiveDto,
      cover,
      title,
      classType,
      entList,
      studyObject,
      objectType,
      serviceNumType,
      publishObject,
      isAllPerson,
    } = values;

    //处理生效日期
    courseEffectiveDto.effectiveTime = courseEffectiveDto.effectiveTime.format(DATEFORMAT);
    //封面
    if (!isEmpty(cover)) {
      finalValue.cover = cover[0].response || cover[0].url; // url：编辑时回显的是url
    }

    if (organizationType === 1) {
      //协会
      //--学习对象
      finalValue.objectType = objectType;
      if (objectType === 1) {
        //企业范围
        finalValue.entList = entList;
      } else if (objectType === 4) {
        //服务号范围
        finalValue.serviceNumType = serviceNumType;
      }
    }

    finalValue.publishObject = publishObject
      ? publishObject.map((item: any) => {
          return {
            name: item.name,
            phone: item.phone,
            id: item.id,
            type: +item.type,
          };
        })
      : undefined;

    // 处理学习包数据
    const clStudyPackageList = cloneDeep(studyPackageList);
    const newStudyPackageList = clStudyPackageList.reduce((prev: any[], curr: any, index: number, array: any[]) => {
      const { studyList } = curr;
      //去除id
      delete curr.id;
      const studyAndExamObj = studyList.reduce(
        (sePrev: { studyList: any[]; examList: any[] }, seCurr: any) => {
          const { type, origin } = seCurr;
          //课件包是没有origin字段的
          if (!isEmpty(origin)) {
            if (String(type) !== '300') {
              seCurr.picTextContent = origin.picTextContent || undefined;
              seCurr.pictextContent = origin.pictextContent || undefined;
              seCurr.picUrl = origin.picUrl || undefined;
              seCurr.vedioId = origin.vedioId || undefined;
              seCurr.vedioInfo = origin.vedioInfo || undefined;
              seCurr.videoList = vedioIdOrVideoInfoTransformToVideoList(origin);
              seCurr.picTextContent = pictextContentToPicTextContent(origin);
            }
            delete seCurr.origin;
          }

          if (String(type) === '300') {
            sePrev.examList.push(seCurr);
          } else {
            sePrev.studyList.push({
              ...seCurr,
              videoList: vedioIdOrVideoInfoTransformToVideoList(seCurr),
              picTextContent: pictextContentToPicTextContent(seCurr),
            });
          }
          return sePrev;
        },
        { examList: [], studyList: [] },
      );
      prev.push({ ...curr, studyList: studyAndExamObj.studyList, examList: studyAndExamObj.examList });
      return prev;
    }, []);

    // const notNullStudyPackageList = requestParamsFormat(newStudyPackageList);

    finalValue = {
      // form字段
      ...finalValue,
      isAllPerson,
      cycleTime,
      courseRuleDto,
      courseEffectiveDto,
      title,
      classType: Array.isArray(classType) ? classType[1] : classType,
      studyObject,
      // publishObject,
      // 其他字段
      entId,
      issueObjectType: 400, //发布对象类型 100所有(全平台) 200关注我的 300加入的 400指定对象
      addSource: organizationType === 1 ? 2 : 1, //1企业2政协
      studyPackageList: newStudyPackageList,
      issue: 1, //1：发布，0：保存
      isCharge: newStudyPackageList.findIndex((item: IStudyPackage) => item.isCharge) > -1 ? 1 : 0, //是否有收费内容0否,1是
    };
    return finalValue;
  };

  const _createCircleStudyPlanApi = (subValue: any) => {
    setLoading(true);
    createCircleStudyPlanNew(subValue)
      .then((res: any) => {
        const { code, data, msg } = res;
        if (code === '200') {
          if (data === 1) {
            confirm({
              title: '发布失败',
              content: msg,
              centered: true,
              okText: '前往',
              onOk: () => {
                if (loginRole == '1' || loginRole == '0') {
                  navigator('/safeService/buyService');
                } else {
                  message.warning('您暂无权限，请联系企业管理人员！');
                }
              },
            });
          } else if (data.promptMessage) {
            confirm({
              title: '发布成功',
              content: data.promptMessage,
              centered: true,
              okText: '前往',
              onOk: () => {
                if (loginRole == '1' || loginRole == '0') {
                  navigator('/safeService/bitAllocation');
                } else {
                  message.warning('您暂无权限，请联系企业管理人员！');
                }
              },
            });
          } else {
            message.success((type === pageOpeTypeEnum['add'] ? '添加' : '编辑') + '成功');
            onSubSuccess?.();
          }
        }
      })
      .finally(() => {
        setLoading(false);
      })
      .catch((err) => {
        console.log('--AddCircleStudyPlan--createFixedStudyPlan--err--:', err);
      });
  };

  // 发布
  const onSubPublish = () => {
    form
      .validateFields()
      .then((values) => {
        console.log('--AddCircleStudyPlan--values--:', values);
        if (isEmpty(values.studyPackageList)) return message.warning('请先添加计划内容');
        if (values.studyPackageList.length > 20) return message.warning('最多只能添加20个学习包');
        if (!dayjs(values.courseEffectiveDto.effectiveTime).isAfter(dayjs())) {
          return message.warning('生效时间最早为次日生效');
        }
        const subValue = dealWidthFormValues(values);

        if (type === pageOpeTypeEnum['edit']) {
          //编辑
          subValue.guid = planCourseId;
        }
        console.log('---subValue--:', subValue);
        if (type === pageOpeTypeEnum['edit'] || !isEmpty(previewDetail)) {
          confirm({
            title: '开启学习计划',
            content:
              subValue.cycleTime === 1
                ? `当前发布生效时间为【${subValue.courseEffectiveDto.effectiveTime}】开始生效，生效后所有驾驶员将变更为红码，并需要完成学习后才可变更安全码颜色，是否确定发布？`
                : `当前发布生效时间为【${subValue.courseEffectiveDto.effectiveTime}】开始生效，是否确定发布？`,
            centered: true,
            onOk: () => {
              _createCircleStudyPlanApi(subValue);
            },
          });
        } else {
          _createCircleStudyPlanApi(subValue);
        }
      })
      .catch((err) => {
        onSubError?.();
        console.log('--AddCircleStudyPlan--form--err--:', err);
      });
  };

  useImperativeHandle(ref, () => ({
    onSubPublish,
  }));

  useEffect(() => {
    // 初始化获取当前定位
    if (type === pageOpeTypeEnum['add']) {
      if (!isEmpty(previewDetail)) {
        //计划模板进来
        // console.log('--AddCircleStudyPlan--previewDetail--:', previewDetail);
        const { cycleDay, name, learnMode, faceImg, guid, isCharge } = previewDetail;
        const initialFormVal: any = {
          cycleTime: Number(cycleDay!),
          courseRuleDto: { studyModel: learnMode === 'order' ? 200 : 100 },
          courseEffectiveDto: { studyTime: 6, effectiveTime: dayjs().add(1, 'day') },
          title: name,
          cover: faceImg ? [{ uid: uuid(), url: faceImg }] : undefined,
          studyMethod: '100',
        };
        if (organizationType === 1) {
          //协会
          initialFormVal.objectType = 1;
          initialFormVal.isAllPerson = 1;
        }
        form.setFieldsValue(initialFormVal);
        dealWidthStudyTemplate(guid, isCharge).then((studyPackageList) => {
          form.setFieldValue('studyPackageList', studyPackageList);
        });
      } else {
        //新增进来
        const initialFormVal: any = {
          cycleTime: 1,
          courseRuleDto: { studyModel: 200 },
          courseEffectiveDto: { studyTime: 6, effectiveTime: dayjs().add(1, 'day') },
          studyMethod: '100',
        };
        learnMethod = '100';
        if (organizationType === 1) {
          //协会
          initialFormVal.objectType = 1;
          initialFormVal.isAllPerson = 1;
        }

        form.setFieldsValue(initialFormVal);
      }
    } else if (type === pageOpeTypeEnum['edit'] && planCourseId) {
      setLoading(true);
      getCircleStudyPlanDetail(planCourseId)
        .then((res: any) => {
          const { data } = res;
          console.log('--AddCircleStudyPlan--edit--data--:', data);
          const initialFormValue: any = {};
          const {
            studyObject,
            objectType,
            entList,
            serviceNumType,
            courseEffectiveDto,
            cover,
            studyPackageList,
            classId,
            title,
            courseRuleDto,
            cycleTime,
            isCharge,
            safePlanPersonVoList,
            isAllPerson,
          } = data;

          // if (organizationType === 1) {
          // 协会 - 学习对象

          initialFormValue.publishObject = safePlanPersonVoList
            ? safePlanPersonVoList.map((item: any) => {
                return {
                  id: item.id,
                  name: item.name,
                  phone: item.phone,
                  type: '1',
                  tab: '1',
                  checked: true,
                  count: 1,
                };
              })
            : undefined;
          // }

          if (organizationType === 1) {
            initialFormValue.isAllPerson = isAllPerson;
          }

          // if (organizationType === 1) {
          //   //协会
          //   //--学习对象
          //   initialFormValue.objectType = objectType;
          //   if (objectType === 1) {
          //     //企业范围
          //     initialFormValue.entList = entList;
          //   } else if (objectType === 4) {
          //     //服务号范围
          //     initialFormValue.serviceNumType = serviceNumType;
          //   }
          // }
          //生效时间
          courseEffectiveDto.effectiveTime = dayjs(courseEffectiveDto.effectiveTime, DATEFORMAT);
          //封面
          if (!isEmpty(cover)) {
            initialFormValue.cover = [{ uid: uuid(), url: cover }];
          }
          //学习包
          const newStudyPackageList = studyPackageList.reduce(
            (prev: IStudyPackage[], curr: IStudyPackage, index: number, array: IStudyPackage[]) => {
              const { studyList, examList, packageType, sourceType } = curr;
              let newStudyList: any[] = studyList || [];
              if (!isEmpty(examList)) {
                newStudyList = [...newStudyList, ...examList!];
              }
              prev.push({
                id: uuid(),
                studyList: newStudyList,
                packageType,
                sourceType,
                isCharge,
                pageType: 'edit',
              });
              return prev;
            },
            [],
          );

          console.log('=============newStudyPackageList=============', newStudyPackageList);

          form.setFieldsValue({
            ...initialFormValue,
            cycleTime: Number(cycleTime),
            title,
            studyPackageList: newStudyPackageList,
            courseEffectiveDto,
            courseRuleDto,
            studyObject,
          });
          learnMethod = '100';
          form.setFieldValue('studyMethod', '100');
          // 分类回显
          getClassViewData().then((data) => {
            // console.log('--data--:', data);
            const parentCode = getParentCode(data, classId);
            form.setFieldValue('classType', [parentCode, classId]);
          });
        })
        .finally(() => {
          setLoading(false);
        })
        .catch((err) => {
          console.log('--AddCircleStudyPlan--getCircleStudyPlanDetail--err--:', err);
        });
    }
  }, [type, planCourseId, organizationType, previewDetail]);

  //添加学习包
  const handleSourceModalChange = (values: Source[], menuActiveKey: string) => {
    const sourceList: IStudyPackage[] = form.getFieldValue('studyPackageList') || [];
    console.log('--添加学习包--values--sourceList---:', values, sourceList);
    sourceModalChange(values, menuActiveKey, sourceList)
      .then((newSourceList: IStudyPackage[]) => {
        console.log('---newSourceList--:', newSourceList);
        form.setFieldValue('studyPackageList', newSourceList);
      })
      .catch((errMsg) => {
        message.warning(errMsg);
      });
  };

  return (
    <Form layout="horizontal" labelAlign="right" form={form} {...formItemLayout}>
      <YmCollaPanes
        collPanesActiveKeys={collPanesActiveKeys}
        // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
        paneKey={0}
        collapsible={false}
        headerTitle="基本信息"
      >
        {organizationType === 1 && (
          <>
            <Form.Item label="学习模式" name="studyMethod" rules={requireRules('请选择学习模式')}>
              <Radio.Group
                defaultValue={learnMethod}
                onChange={(e) => {
                  onStudyPlanMethodChange(e.target.value);
                  console.log(e.target.value, learnMethod, '打印看看现在是什么b');
                }}
                disabled={type !== pageOpeTypeEnum['add']}
              >
                <Radio value="100">线上学习</Radio>
                <Radio value="200">线下培训</Radio>
              </Radio.Group>
            </Form.Item>
          </>
        )}
        <Form.Item label="类型" required>
          <Space size={16}>
            <Select
              style={{ width: '120px' }}
              value={studyPlanType}
              onChange={(e) => {
                console.log(e, onStudyPlanTypeChange, '打印看看类型监听');
                onStudyPlanTypeChange(e);
              }}
              disabled={type !== pageOpeTypeEnum['add'] || !isEmpty(previewDetail)}
              options={studyPlanTypeOptions}
            />
            <>
              每
              <Form.Item noStyle name="cycleTime">
                <Select options={circleTimeOptions} />
              </Form.Item>
              日一学
            </>
          </Space>
        </Form.Item>
        <Form.Item label="计划名称" name="title" rules={requireRules('请输入计划名称')}>
          <Input showCount maxLength={18} placeholder="请输入"></Input>
        </Form.Item>
        <Form.Item label="分类" name="classType" {...classFormItemProps} rules={requireRules('请选择分类')}>
          <CategoryCascader />
        </Form.Item>
        <Form.Item label="学习机制" name={['courseRuleDto', 'studyModel']} rules={requireRules('请选择分类')}>
          <Radio.Group disabled={type !== pageOpeTypeEnum['add'] || !isEmpty(previewDetail)}>
            <Radio value={200}>顺序轮学</Radio>
            <Radio value={100}>随机抽学</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="学习时间"
          required
          shouldUpdate={(prevValues, currentValues) =>
            prevValues.cycleTime !== currentValues.cycleTime ||
            prevValues.courseEffectiveDto !== currentValues.courseEffectiveDto
          }
        >
          {({ getFieldValue }) => (
            <Space size={16}>
              <Form.Item noStyle name={['courseEffectiveDto', 'studyTime']} rules={requireRules('请选择学习时间')}>
                <Select style={{ width: '120px' }} options={styleTimeOptions()} />
              </Form.Item>
              <span>
                至{getFieldValue('cycleTime')}日后
                {getFieldValue('courseEffectiveDto') && getFieldValue('courseEffectiveDto').studyTime}点
              </span>
            </Space>
          )}
        </Form.Item>
        <Form.Item label="生效时间" required>
          <Space>
            <Form.Item noStyle name={['courseEffectiveDto', 'effectiveType']} initialValue={2}>
              <Select
                style={{ width: 120 }}
                disabled
                options={[
                  { value: 2, label: '指定日期生效' },
                  { value: 1, label: '立即生效' },
                ]}
              />
            </Form.Item>
            <Form.Item noStyle name={['courseEffectiveDto', 'effectiveTime']} rules={requireRules('请选择生效日期')}>
              <DatePicker disabledDate={(currentDate) => currentDate.isBefore(dayjs().endOf('day'))} />
            </Form.Item>
          </Space>
        </Form.Item>
        {/* <Form.Item  name="isAllPerson" label="学习对象" rules={requireRules('请选择学习对象人员')}>
          {organizationType === 1 ? <YmRegisterPersonSelect /> : <YmEntChoiceStaffModal />}
        </Form.Item>
        <Form.Item name="publishObject" label="学习对象" rules={requireRules('请选择学习对象人员')}>
          {organizationType === 1 ? <YmRegisterPersonSelect /> : <YmEntChoiceStaffModal />}
        </Form.Item> */}

        {organizationType === 1 ? (
          <Form.Item label="学习对象" required>
            <Space>
              <Form.Item name="isAllPerson" noStyle>
                <Select
                  onChange={(e) => {
                    form.setFieldValue('publishObject', undefined);
                  }}
                  style={{ width: 200 }}
                  options={[
                    { label: '全部备案人员', value: 1 },
                    { label: '部分备案人员', value: 0 },
                  ]}
                />
              </Form.Item>
              <Form.Item
                noStyle
                shouldUpdate={(prevValues, currentValues) => prevValues.isAllPerson !== currentValues.isAllPerson}
              >
                {({ getFieldValue }) =>
                  getFieldValue('isAllPerson') === 0 ? (
                    <Space>
                      <Form.Item name="publishObject" noStyle rules={requireRules('请选择学习对象人员')}>
                        <YmRegisterPersonSelect />
                      </Form.Item>
                    </Space>
                  ) : null
                }
              </Form.Item>
            </Space>
          </Form.Item>
        ) : (
          <Form.Item name="publishObject" label="学习对象" rules={requireRules('请选择学习对象人员')}>
            <YmEntChoiceStaffModal />
          </Form.Item>
        )}

        <Form.Item label="封面图">
          <Form.Item name="cover" noStyle>
            <YmUpload maxCount={1} cardWidth={140} cardHeight={140} accept="image/*" customRequest={customRequest}>
              上传图片
            </YmUpload>
          </Form.Item>
          <p className="safe-edu_upload_warning">图片宽高比例以1.875:1为宜，如：750*400</p>
        </Form.Item>
      </YmCollaPanes>
      <YmCollaPanes
        collPanesActiveKeys={collPanesActiveKeys}
        // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
        paneKey={1}
        collapsible={false}
        headerTitle="计划内容"
        contentClass={OStyle.cus_item_content}
        extra={
          !isEmpty(tradeMap) && (
            <Button
              style={{ marginRight: '16px' }}
              size="small"
              type="primary"
              shape="round"
              onClick={() => {
                setModalOpen(Math.random());
              }}
            >
              添加
            </Button>
          )
        }
      >
        <SourceSelectModal
          openDep={modalOpen}
          preSet="学习计划"
          params={{ entId }}
          columnsRender={{ tradeMap }}
          onChange={handleSourceModalChange} //放在Form.Item里面只会识别第一个参数作为value
          // modalWidth={1176}
          // menuLeftWidth={168}
        />
        <Form.Item name="studyPackageList" noStyle>
          <StudyPackage type={type} />
        </Form.Item>
      </YmCollaPanes>
    </Form>
  );
});

export default AddCircleStudyPlan;
